/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.futurefeed.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import ro.futurefeed.model.Feed;
import ro.futurefeed.api.FeedStatus;
import ro.futurefeed.model.User;
import ro.futurefeed.repository.FeedRepository;
import ro.futurefeed.repository.UserRepository;
import ro.futurefeed.util.DateUtil;

/**
 *
 * @author Georgian
 */
@Component
@Path("/publish/")
public class FeedPublisherServiceImpl implements FeedPublisherService{
    private static final Logger log = Logger.getLogger("FeedPublisherService");
    
    @Autowired
    private FacebookService facebookService;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private FeedRepository feedRepository;
    
    @GET
    @Override
    public Response execute() {
        Long start = System.currentTimeMillis();
        String currentDateAtGMTString = DateUtil.getCurrentDateAtGMTString();
        log.info("Executing Cron Publish job for " + currentDateAtGMTString);
        List<Feed> feedsToProcess = feedRepository.getFeeds(currentDateAtGMTString, FeedStatus.WAITING);
        log.info("No of feeds to process: " + feedsToProcess.size());
        for(Feed feed : feedsToProcess){
            User user = userRepository.findByKey(feed.getUserKey());
            String postId = null;
            FeedStatus status = null;
            try{
                postId = facebookService.postWallFeed(user.getAccessToken(), feed.getDestination(), feed.getContent());
                status = FeedStatus.PUBLISHED;
            }catch(Exception e){
                log.severe("Error posting feed id = " + feed.getId() + ":\n" + e);
                status = FeedStatus.ERROR;
            }finally {
                feed.setFbId(postId);
                feed.setStatus(status);
                feedRepository.update(feed);
                //TODO send email 
            }
        }
        Long durationInMs = System.currentTimeMillis() - start;
        return Response.status(Response.Status.OK).entity("OK. Execution time was " + durationInMs + " ms.").build();
    }
}
